package com.lancoo.znbkxx.teacher.aibkTestCoach.kBase

import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter

/**
 * 创建FragmentAdapter继承FragmentPagerAdapter，并重写相关方法
 */
class KBaseFragmentPagerAdapter : FragmentPagerAdapter {
    private var fm: FragmentManager
    private var fragmentList: MutableList<Fragment>
    private var fragmentTitles: MutableList<String>? = null

    constructor(fm: FragmentManager, fragmentList: MutableList<Fragment>) : super(fm) {
        this.fm = fm
        this.fragmentList = fragmentList
    }

    constructor(fm: FragmentManager, fragmentList: MutableList<Fragment>, fragmentTitles: MutableList<String>?) : super(fm) {
        this.fm = fm
        this.fragmentList = fragmentList
        this.fragmentTitles = fragmentTitles
    }

    override fun getItem(position: Int): Fragment {
        //        Bundle bundle = new Bundle();
//        bundle.putString("id","" + position);
//        fragment.setArguments(bundle);
        return fragmentList[position]
    }

    override fun getCount(): Int {
        return fragmentList.size
    }

    override fun instantiateItem(container: ViewGroup, position: Int): Any {
        // 将实例化的fragment进行显示即可。
        val fragment = super.instantiateItem(container, position) as Fragment
        //        fm.beginTransaction().show(fragment).commit();
        fm.beginTransaction().show(fragment).commitAllowingStateLoss()
        return fragment
    }

    override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
//            super.destroyItem(container, position, object);// 注释父类方法
        val fragment: Fragment = fragmentList[position] // 获取要销毁的fragment
        //        fm.beginTransaction().hide(fragment).commit();// 将其隐藏即可，并不需要真正销毁，这样fragment状态就得到了保存
        fm.beginTransaction().hide(fragment).commitAllowingStateLoss()
    }

    override fun getPageTitle(position: Int): CharSequence? {
        return fragmentTitles!![position]
    }
}